package com.imgrate.migration.controller;

import com.imgrate.migration.entity.Server;
import com.imgrate.migration.service.ServerService;
import com.imgrate.migration.service.SshService;
import com.imgrate.migration.dto.DiskInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/servers")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class ServerTestController {
    
    private final ServerService serverService;
    private final SshService sshService;
    
    /**
     * 测试服务器连接
     * @param id 服务器ID
     * @return 连接测试结果
     */
    @PostMapping("/{id}/test-connection")
    public ResponseEntity<SshService.ConnectionResult> testServerConnection(@PathVariable Long id) {
        try {
            log.info("开始测试服务器连接，服务器ID: {}", id);
            
            // 获取服务器信息
            Optional<Server> serverOpt = serverService.getServerById(id);
            if (!serverOpt.isPresent()) {
                log.warn("未找到服务器，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            Server server = serverOpt.get();
            
            // 测试连接
            SshService.ConnectionResult result = sshService.testConnection(server);
            
            if (result.isSuccess()) {
                log.info("服务器连接测试成功: {} ({})", server.getName(), server.getHostname());
            } else {
                log.warn("服务器连接测试失败: {} ({}) - {}", server.getName(), server.getHostname(), result.getMessage());
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("测试服务器连接时发生错误: {}", e.getMessage(), e);
            SshService.ConnectionResult errorResult = new SshService.ConnectionResult();
            errorResult.setSuccess(false);
            errorResult.setMessage("测试连接时发生错误: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResult);
        }
    }
    
    /**
     * 获取Linux服务器磁盘信息
     * @param id 服务器ID
     * @return 磁盘信息
     */
    @GetMapping("/{id}/disk-info/linux")
    public ResponseEntity<SshService.CommandResult> getLinuxDiskInfo(@PathVariable Long id) {
        try {
            log.info("开始获取Linux服务器磁盘信息，服务器ID: {}", id);
            
            // 获取服务器信息
            Optional<Server> serverOpt = serverService.getServerById(id);
            if (!serverOpt.isPresent()) {
                log.warn("未找到服务器，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            Server server = serverOpt.get();
            
            // 获取磁盘信息
            SshService.CommandResult result = sshService.getLinuxDiskInfo(server);
            
            if (result.isSuccess()) {
                log.info("获取Linux服务器磁盘信息成功: {} ({})", server.getName(), server.getHostname());
            } else {
                log.warn("获取Linux服务器磁盘信息失败: {} ({}) - {}", server.getName(), server.getHostname(), result.getMessage());
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取Linux服务器磁盘信息时发生错误: {}", e.getMessage(), e);
            SshService.CommandResult errorResult = new SshService.CommandResult();
            errorResult.setSuccess(false);
            errorResult.setMessage("获取磁盘信息时发生错误: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResult);
        }
    }
    
    /**
     * 获取Windows服务器磁盘信息
     * @param id 服务器ID
     * @return 磁盘信息
     */
    @GetMapping("/{id}/disk-info/windows")
    public ResponseEntity<SshService.CommandResult> getWindowsDiskInfo(@PathVariable Long id) {
        try {
            log.info("开始获取Windows服务器磁盘信息，服务器ID: {}", id);
            
            // 获取服务器信息
            Optional<Server> serverOpt = serverService.getServerById(id);
            if (!serverOpt.isPresent()) {
                log.warn("未找到服务器，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            Server server = serverOpt.get();
            
            // 获取磁盘信息
            SshService.CommandResult result = sshService.getWindowsDiskInfo(server);
            
            if (result.isSuccess()) {
                log.info("获取Windows服务器磁盘信息成功: {} ({})", server.getName(), server.getHostname());
            } else {
                log.warn("获取Windows服务器磁盘信息失败: {} ({}) - {}", server.getName(), server.getHostname(), result.getMessage());
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取Windows服务器磁盘信息时发生错误: {}", e.getMessage(), e);
            SshService.CommandResult errorResult = new SshService.CommandResult();
            errorResult.setSuccess(false);
            errorResult.setMessage("获取磁盘信息时发生错误: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResult);
        }
    }
    
    /**
     * 获取Linux服务器目录结构
     * @param id 服务器ID
     * @param path 路径
     * @return 目录结构
     */
    @GetMapping("/{id}/directory-structure/linux")
    public ResponseEntity<SshService.CommandResult> getLinuxDirectoryStructure(
            @PathVariable Long id, 
            @RequestParam(defaultValue = "/") String path) {
        try {
            log.info("开始获取Linux服务器目录结构，服务器ID: {}, 路径: {}", id, path);
            
            // 获取服务器信息
            Optional<Server> serverOpt = serverService.getServerById(id);
            if (!serverOpt.isPresent()) {
                log.warn("未找到服务器，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            Server server = serverOpt.get();
            
            // 获取目录结构
            SshService.CommandResult result = sshService.getLinuxDirectoryStructure(server, path);
            
            if (result.isSuccess()) {
                log.info("获取Linux服务器目录结构成功: {} ({})", server.getName(), server.getHostname());
            } else {
                log.warn("获取Linux服务器目录结构失败: {} ({}) - {}", server.getName(), server.getHostname(), result.getMessage());
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取Linux服务器目录结构时发生错误: {}", e.getMessage(), e);
            SshService.CommandResult errorResult = new SshService.CommandResult();
            errorResult.setSuccess(false);
            errorResult.setMessage("获取目录结构时发生错误: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResult);
        }
    }
    
    /**
     * 获取Windows服务器目录结构
     * @param id 服务器ID
     * @param path 路径
     * @return 目录结构
     */
    @GetMapping("/{id}/directory-structure/windows")
    public ResponseEntity<SshService.CommandResult> getWindowsDirectoryStructure(
            @PathVariable Long id, 
            @RequestParam(defaultValue = "C:\\") String path) {
        try {
            log.info("开始获取Windows服务器目录结构，服务器ID: {}, 路径: {}", id, path);
            
            // 获取服务器信息
            Optional<Server> serverOpt = serverService.getServerById(id);
            if (!serverOpt.isPresent()) {
                log.warn("未找到服务器，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            Server server = serverOpt.get();
            
            // 获取目录结构
            SshService.CommandResult result = sshService.getWindowsDirectoryStructure(server, path);
            
            if (result.isSuccess()) {
                log.info("获取Windows服务器目录结构成功: {} ({})", server.getName(), server.getHostname());
            } else {
                log.warn("获取Windows服务器目录结构失败: {} ({}) - {}", server.getName(), server.getHostname(), result.getMessage());
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取Windows服务器目录结构时发生错误: {}", e.getMessage(), e);
            SshService.CommandResult errorResult = new SshService.CommandResult();
            errorResult.setSuccess(false);
            errorResult.setMessage("获取目录结构时发生错误: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResult);
        }
    }
}